<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<link href="<c:url value="/css/style.css"/>" rel="stylesheet">
<!DOCTYPE html>
<html>
<head>
    <title>考勤管理</title>
    <style>
        /* 添加模态框显示样式 */
        .modal1 {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }

        .modal1-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 25px;
            border: 1px solid #888;
            width: 500px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            max-height: 80vh;
            overflow-y: auto;
        }

        .close1 {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close1:hover {
            color: #333;
        }

        /* 表单样式 */
        .form1-group1 {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .form1-group1 label {
            display: block;
            margin-bottom: 5px;
            width: 120px;
            margin-right: 15px;
            text-align: right;
        }

        .form1-group1 input,
        .form1-group1 select,
        .form1-group1 textarea {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            flex: 1;
        }

        /* 考勤状态标签样式 */
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-present { background-color: #d4edda; color: #155724; }
        .status-late { background-color: #fff3cd; color: #856404; }
        .status-absent { background-color: #f8d7da; color: #721c24; }
        .status-leave { background-color: #cce5ff; color: #004085; }

        /* 筛选区域样式 */
        .filter-section {
            background-color: #fff;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .filter-row {
            display: flex;
            gap: 15px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }

        .filter-group {
            flex: 1;
            min-width: 200px;
        }

        .filter-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #2c3e50;
        }

        .filter-group input,
        .filter-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .filter-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="sidebar">
        <h2>员工管理系统</h2>
        <div class="user-info">
            <p>欢迎, ${user.username}</p>
            <a href="logout">退出登录</a>
        </div>
        <ul class="menu">
            <c:if test="${user.role == 'admin'}">
                <li><a href="employee?action=list">员工管理</a></li>
                <li><a href="#">薪资管理</a></li>
            </c:if>
            <li class="active"><a href="attendance?action=list">考勤管理</a></li>
            <li><a href="#">修改密码</a></li>
        </ul>
    </div>

    <div class="main-content">
        <h1>考勤管理</h1>

        <div class="filter-section">
            <form action="attendance" method="get" class="filter-form">
                <input type="hidden" name="action" value="search">

                <div class="filter-row">
                    <div class="filter-group">
                        <label for="empId">员工ID:</label>
                        <input type="text" id="empId" name="empId" value="${param.empId}">
                    </div>
                    <div class="filter-group">
                        <label for="name">姓名:</label>
                        <input type="text" id="name" name="name" value="${param.name}">
                    </div>
                    <div class="filter-group">
                        <label for="status">考勤状态:</label>
                        <select id="status" name="status">
                            <option value="">全部</option>
                            <option value="正常" ${param.status == '正常' ? 'selected' : ''}>正常</option>
                            <option value="迟到" ${param.status == '迟到' ? 'selected' : ''}>迟到</option>
                            <option value="早退" ${param.status == '早退' ? 'selected' : ''}>早退</option>
                            <option value="缺勤" ${param.status == '缺勤' ? 'selected' : ''}>缺勤</option>
                            <option value="请假" ${param.status == '请假' ? 'selected' : ''}>请假</option>
                        </select>
                    </div>
                </div>

                <div class="filter-row">
                    <div class="filter-group">
                        <label for="startDate">开始日期:</label>
                        <input type="date" id="startDate" name="startDate" value="${param.startDate}">
                    </div>
                    <div class="filter-group">
                        <label for="endDate">结束日期:</label>
                        <input type="date" id="endDate" name="endDate" value="${param.endDate}">
                    </div>
                    <div class="filter-group">
                        <label>&nbsp;</label>
                        <div class="filter-actions">
                            <button type="submit" class="btn">搜索</button>
                            <button type="button" class="btn" onclick="resetFilter()">重置</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="toolbar">
            <div></div>
            <c:if test="${user.role == 'admin'}">
                <button id="addAttendanceBtn" class="btn">添加考勤记录</button>
            </c:if>
        </div>

        <c:if test="${not empty error}">
            <div class="error-message">${error}</div>
        </c:if>
        <c:if test="${not empty success}">
            <div class="success-message">${success}</div>
        </c:if>

        <table class="data-table">
            <thead>
            <tr>
                <th>ID</th>
                <th>员工ID</th>
                <th>员工姓名</th>
                <th>考勤日期</th>
                <th>考勤状态</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <c:forEach items="${attendances}" var="att">
                <tr>
                    <td>${att.attendanceId}</td>
                    <td>${att.empId}</td>
                    <td>${att.empName}</td>
                    <td><fmt:formatDate value="${att.recordDate}" pattern="yyyy-MM-dd" /></td>
                    <td>
                        <c:choose>
                            <c:when test="${att.status == '正常'}">
                                <span class="status-badge status-present">${att.status}</span>
                            </c:when>
                            <c:when test="${att.status == '迟到' || att.status == '早退'}">
                                <span class="status-badge status-late">${att.status}</span>
                            </c:when>
                            <c:when test="${att.status == '缺勤'}">
                                <span class="status-badge status-absent">${att.status}</span>
                            </c:when>
                            <c:when test="${att.status == '请假'}">
                                <span class="status-badge status-leave">${att.status}</span>
                            </c:when>
                            <c:otherwise>
                                ${att.status}
                            </c:otherwise>
                        </c:choose>
                    </td>
                    <td>${att.leaveReason}</td>
                    <td>
                        <c:if test="${user.role == 'admin'}">
                            <button class="btn-small edit-btn"
                                    data-id="${att.attendanceId}"
                                    data-emp-id="${att.empId}"
                                    data-emp-name="${att.empName}"
                                    data-date="<fmt:formatDate value='${att.recordDate}' pattern='yyyy-MM-dd' />"
                                    data-status="${att.status}"
                                    data-reason="${att.leaveReason}">
                                编辑
                            </button>
                            <form action="attendance" method="post" style="display:inline;">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="attendanceId" value="${att.attendanceId}">
                                <button type="submit" class="btn-small btn-danger"
                                        onclick="return confirm('确定删除该考勤记录吗？')">删除</button>
                            </form>
                        </c:if>
                    </td>
                </tr>
            </c:forEach>

            <c:if test="${empty attendances}">
                <tr>
                    <td colspan="7" style="text-align: center;">没有找到考勤记录</td>
                </tr>
            </c:if>
            </tbody>
        </table>
    </div>
</div>

<!-- 添加/编辑考勤模态框 -->
<div id="attendanceModal" class="modal1">
    <div class="modal1-content">
        <span class="close1">&times;</span>
        <h2 id="modalTitle">添加考勤记录</h2>
        <form action="attendance" method="post" id="attendanceForm">
            <input type="hidden" name="action" value="add" id="formAction">
            <input type="hidden" name="attendanceId" id="attendanceId">

            <div class="form1-group1">
                <label for="modalEmpId">员工ID:</label>
                <input type="text" id="modalEmpId" name="empId" required>
            </div>

            <div class="form1-group1">
                <label for="modalEmpName">员工姓名:</label>
                <input type="text" id="modalEmpName" readonly>
            </div>

            <div class="form1-group1">
                <label for="modalRecordDate">考勤日期:</label>
                <input type="date" id="modalRecordDate" name="recordDate" required>
            </div>

            <div class="form1-group1">
                <label for="modalStatus">考勤状态:</label>
                <select id="modalStatus" name="status" required>
                    <option value="正常">正常</option>
                    <option value="迟到">迟到</option>
                    <option value="早退">早退</option>
                    <option value="缺勤">缺勤</option>
                    <option value="请假">请假</option>
                </select>
            </div>

            <div class="form1-group1">
                <label for="modalLeaveReason">备注/原因:</label>
                <textarea id="modalLeaveReason" name="leaveReason" rows="3"></textarea>
            </div>

            <div class="form1-group1">
                <button type="submit" class="btn">保存记录</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 模态框控制
        const modal = document.getElementById("attendanceModal");
        const addBtn = document.getElementById("addAttendanceBtn");
        const closeBtn = document.querySelector(".close1");
        const modalTitle = document.getElementById("modalTitle");
        const formAction = document.getElementById("formAction");
        const attendanceId = document.getElementById("attendanceId");
        const modalEmpId = document.getElementById("modalEmpId");
        const modalEmpName = document.getElementById("modalEmpName");
        const modalRecordDate = document.getElementById("modalRecordDate");
        const modalStatus = document.getElementById("modalStatus");
        const modalLeaveReason = document.getElementById("modalLeaveReason");

        // 设置今天的日期为默认值
        const today = new Date().toISOString().split('T')[0];
        modalRecordDate.value = today;

        // 打开添加模态框
        if (addBtn) {
            addBtn.addEventListener("click", function() {
                resetForm();
                modalTitle.textContent = "添加考勤记录";
                formAction.value = "add";
                modal.style.display = "block";
            });
        }

        // 关闭模态框
        if (closeBtn) {
            closeBtn.addEventListener("click", function() {
                modal.style.display = "none";
            });
        }

        // 点击模态框外部关闭
        window.addEventListener("click", function(event) {
            if (event.target === modal) {
                modal.style.display = "none";
            }
        });

        // 编辑按钮点击事件
        document.querySelectorAll('.edit-btn').forEach(button => {
            button.addEventListener('click', function() {
                const id = this.dataset.id;
                const empId = this.dataset.empId;
                const empName = this.dataset.empName;
                const date = this.dataset.date;
                const status = this.dataset.status;
                const reason = this.dataset.reason || '';

                console.log("Editing record:", {id, empId, date, status, reason});

                document.getElementById('attendanceId').value = id;
                document.getElementById('modalEmpId').value = empId;
                document.getElementById('modalEmpName').value = empName;
                document.getElementById('modalRecordDate').value = date;
                document.getElementById('modalStatus').value = status;
                document.getElementById('modalLeaveReason').value = reason;

                document.getElementById('modalTitle').textContent = "编辑考勤记录";
                document.getElementById('formAction').value = "update";
                document.getElementById('attendanceModal').style.display = "block";
            });
        });

        // 重置表单
        function resetForm() {
            document.getElementById("attendanceForm").reset();
            attendanceId.value = "";
            modalEmpName.value = "";
            modalRecordDate.value = today; // 重置为今天
        }

        // 员工ID输入时自动获取姓名
        if (modalEmpId) {
            modalEmpId.addEventListener('blur', function() {
                const empId = this.value;
                if (empId) {
                    fetchEmployeeName(empId);
                } else {
                    modalEmpName.value = "";
                }
            });
        }

        // 获取员工姓名的AJAX请求
        function fetchEmployeeName(empId) {
            fetch('employee?action=getEmployeeName&empId=' + empId)
                .then(response => response.text())
                .then(name => {
                    modalEmpName.value = name || "员工不存在";
                })
                .catch(error => {
                    console.error('获取员工姓名失败:', error);
                    modalEmpName.value = "获取失败";
                });
        }

        // 重置筛选条件
        window.resetFilter = function() {
            document.getElementById('empId').value = '';
            document.getElementById('name').value = '';
            document.getElementById('status').value = '';
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';
            // 提交表单重置
            document.querySelector('.filter-form').submit();
        }
    });
</script>
</body>
</html>